package com.tianzeculture.stagebao.activity.personal;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.tianzeculture.stagebao.R;
import com.tianzeculture.stagebao.base.BaseActivity;
import com.tianzeculture.stagebao.bean.ArtistsDetailedBean;
import com.tianzeculture.stagebao.bean.JobBean;
import com.tianzeculture.stagebao.bean.ResultBean;
import com.tianzeculture.stagebao.bean.User;
import com.tianzeculture.stagebao.dialog.PhotoDialog;
import com.tianzeculture.stagebao.dialog.SexDialog;
import com.tianzeculture.stagebao.net.CommonRestUsage;
import com.tianzeculture.stagebao.net.UserRestUsage;
import com.tianzeculture.stagebao.network.Request;
import com.tianzeculture.stagebao.network.enity.MSG;
import com.tianzeculture.stagebao.network.util.ToastUtil;
import com.tianzeculture.stagebao.popwindow.CityPickerPopWindow;
import com.tianzeculture.stagebao.util.PhotoUtils;
import com.tianzeculture.stagebao.util.StatusBarUtil;
import com.tianzeculture.stagebao.util.Util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

import static com.tianzeculture.stagebao.net.base.AppBaseRestUsageV2.PICTURE_URL;

/**
 * Created by Administrator on 2018/6/15 0015.
 * 我的主页
 */

public class PersonalInfoActivity extends BaseActivity implements SexDialog.OnSelectClickListener,
        CityPickerPopWindow.CityPickListener {


    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;
    private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0x03;
    private static final int STORAGE_PERMISSIONS_REQUEST_CODE = 0x04;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    private Uri imageUri;
    private Uri cropImageUri;

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.layout_root)
    RelativeLayout layout_root;
    @BindView(R.id.ivHead)
    CircleImageView ivHead;
    @BindView(R.id.layoutNickName)
    LinearLayout layoutNickName;
    @BindView(R.id.tvNickName)
    TextView tvNickName;
    @BindView(R.id.tvAccount)
    TextView tvAccount;
    @BindView(R.id.layoutSex)
    LinearLayout layoutSex;
    @BindView(R.id.tvSex)
    TextView tvSex;
    @BindView(R.id.layoutAddress)
    LinearLayout layoutAddress;
    @BindView(R.id.tvCity)
    TextView tvCity;
    @BindView(R.id.layoutJob)
    LinearLayout layoutJob;
    @BindView(R.id.layoutOther)
    LinearLayout layoutOther;
    @BindView(R.id.tvJob)
    TextView tvJob;
    @BindView(R.id.tvName)
    TextView tvName;

    @Request
    UserRestUsage userRestUsage = null;
    private int myInfo = 101;//获取个人信息
    private int updateMyself = 102;//更新用户信息
    private int updateHeader = 103;//更新头像


    @Request
    CommonRestUsage commonRestUsage = null;

    private int industryList = 104;//工作列表
    List<JobBean> allJobBeen = null;


    @Override
    public void initUI() {
        super.initUI();
        StatusBarUtil.setWindowStatusBarColor(PersonalInfoActivity.this, R.color.colorGray_F8);
        tvTitle.setText("我的主页");
        if (Util.JOB == 1) {
            tvName.setText("公司名称");
            layoutSex.setVisibility(View.GONE);
//            layoutJob.setVisibility(View.GONE);
            layoutOther.setVisibility(View.GONE);
        } else {
            tvName.setText("昵称");
            layoutSex.setVisibility(View.VISIBLE);
//            layoutJob.setVisibility(View.VISIBLE);
            layoutOther.setVisibility(View.VISIBLE);
        }
        //初始化用户数据
        updateUserInfo(Util.user);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        commonRestUsage.industryList(industryList);
        userRestUsage.myInfo(myInfo, Util.UserId);
    }


    /**
     * 更新用户信息
     *
     * @param user
     */
    private void updateUserInfo(User user) {
        Log.e("图片地址", Util.IMAGE_URL + user.getImgurl());
        Glide.with(this).load(PICTURE_URL + user.getImgurl()).
                diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .error(R.mipmap.icon_head)
                .placeholder(R.mipmap.icon_head)
                .dontAnimate()
                .into(ivHead);
        tvNickName.setText(user.getNickname());
        tvAccount.setText(Util.Uid);
        if ("0".equals(user.getSex()))
            tvSex.setText("女");
        else
            tvSex.setText("男");
        tvCity.setText(user.getAddress());
//        if (!"".equals(user.getIndustry())) {
//            if (allJobBeen == null)
//                return;
//            for (int i = 0; i < allJobBeen.size(); i++) {
////                if (user.getIndustry().equals(allJobBeen.get(i).getId())) {
//                tvJob.setText(allJobBeen.get(i).getName());
////                }
//            }
//        }
    }

    /**
     * 处理图片并上传
     *
     * @param imgPath
     */
    private void handleImg(String imgPath) {
        String type = imgPath.endsWith(".png") ? "png" : "jpeg";
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        Map<String, String> params = new HashMap<>();
        params.put("photoImgFile", bitmap2StrByBase64(bitmap, type));
        bitmap.recycle();

        userRestUsage.updateUserInfo(updateHeader, params);
    }

    /**
     * 通过Base32将Bitmap转换成Base64字符串
     *
     * @param bit
     * @return
     */
    public String bitmap2StrByBase64(Bitmap bit, String type) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return
//                "data:image/" + type + ";base64," +
                Base64.encodeToString(bytes, Base64.DEFAULT);
    }


    @OnClick({R.id.ivHead, R.id.layoutNickName, R.id.layoutSex, R.id.layoutAddress, R.id.layoutJob, R.id.layoutOther})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivHead:
                PhotoDialog photoDialog = new PhotoDialog(PersonalInfoActivity.this);
                photoDialog.setOnSelectClickListener(new PhotoDialog.OnSelectClickListener() {
                    @Override
                    public void onOk(boolean isTakePic) {
                        if (isTakePic) {
                            autoObtainCameraPermission();
                        } else {
                            autoObtainStoragePermission();
                        }
                    }

                    @Override
                    public void onCancel() {
                    }
                });
                photoDialog.show();
                break;
            case R.id.layoutNickName:
                startActivityForResult(new Intent(PersonalInfoActivity.this,
                        EditNickNameActivity.class), Util.CHOOSE_NICKNAME);
                break;
            case R.id.layoutSex:
                SexDialog sexDialog = new SexDialog(PersonalInfoActivity.this);
                sexDialog.setOnSelectClickListener(this);
                sexDialog.show();
                break;
            case R.id.layoutAddress:
                CityPickerPopWindow cityPickerPopWindow = new CityPickerPopWindow(PersonalInfoActivity.this);
                cityPickerPopWindow.showPopupWindow(layout_root);
                cityPickerPopWindow.setCityPickListener(this);
                break;
            case R.id.layoutOther:
                startActivity(new Intent(this, EditOfferActivity.class));
                break;
        }

    }

    @Override
    public void refreshUI(int taskId, MSG msg) {
        super.refreshUI(taskId, msg);
//        if (taskId == industryList) {
////            if (msg.getData()) {
////                ResultBean resultBean = (ResultBean) msg.getObj();
////                allJobBeen = resultBean.getList();
////            }
//        } else
        if (taskId == myInfo) {
            if (msg.getData()) {
                ArtistsDetailedBean resultBean = (ArtistsDetailedBean) msg.getObj();
                User user = resultBean.getUser();
                if (user != null)
                    Util.user = user;
                updateUserInfo(Util.user);
            }
        } else if (taskId == updateMyself) {
            if (msg.getData()) {
                userRestUsage.myInfo(myInfo, Util.UserId);
            }
        } else if (taskId == updateHeader) {
            if (msg.getData()) {
                userRestUsage.myInfo(myInfo, Util.UserId);
            }
        }
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_personal_info;
    }


    /**
     * 自动获取相机权限
     */
    private void autoObtainCameraPermission() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                ToastUtil.showShort(this, "您已经拒绝过一次");
            }
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE}, CAMERA_PERMISSIONS_REQUEST_CODE);
        } else {//有权限直接调用系统相机拍照
            if (hasSdcard()) {
                imageUri = Uri.fromFile(fileUri);
                //通过FileProvider创建一个content类型的Uri
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(PersonalInfoActivity.this,
                            "com.tianzeculture.stagebao.FileProvider", fileUri);
                }
                PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
            } else {
                ToastUtil.showShort(this, "设备没有SD卡！");
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            //调用系统相机申请拍照权限回调
            case CAMERA_PERMISSIONS_REQUEST_CODE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (hasSdcard()) {
                        imageUri = Uri.fromFile(fileUri);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            imageUri = FileProvider.getUriForFile(PersonalInfoActivity.this,
                                    "com.tianzeculture.stagebao.FileProvider", fileUri);
                        //通过FileProvider创建一个content类型的Uri
                        PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                    } else {
                        ToastUtil.showShort(this, "设备没有SD卡！");
                    }
                } else {
                    ToastUtil.showShort(this, "请允许打开相机！！");
                }
                break;


            }
            //调用系统相册申请Sdcard权限回调
            case STORAGE_PERMISSIONS_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
                } else {
                    ToastUtil.showShort(this, "请允许打操作SDCard！！");
                }
                break;
            default:
        }
    }

    private static final int OUTPUT_X = 480;
    private static final int OUTPUT_Y = 480;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //拍照完成回调
                case CODE_CAMERA_REQUEST:
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1,
                            OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    break;
                //访问相册完成回调
                case CODE_GALLERY_REQUEST:
                    if (hasSdcard()) {
                        cropImageUri = Uri.fromFile(fileCropUri);
                        Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            newUri = FileProvider.getUriForFile(this,
                                    "com.tianzeculture.stagebao.FileProvider", new File(newUri.getPath()));
                        }
                        PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1,
                                OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    } else {
                        ToastUtil.showShort(this, "设备没有SD卡！");
                    }
                    break;
                //截图
                case CODE_RESULT_REQUEST:
                    Bitmap bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);
                    if (bitmap != null) {
                        showImages(bitmap);
                        handleImg(cropImageUri.getPath());
                    }
                    break;
                default:
            }
        } else if (resultCode == Util.CHOOSE_JOB) {   //选择职业
            String job = data.getStringExtra("JOB");
            tvJob.setText(job);
            User user = Util.user;
            user.setIndustry(job);
            userRestUsage.updateUserInfo(updateMyself, user);
        } else if (resultCode == Util.CHOOSE_NICKNAME) {
            Bundle bundle = data.getExtras();
            String nickName = bundle.getString("NICKNAME");
            tvNickName.setText(nickName);
            User user = Util.user;
            user.setNickname(nickName);
            userRestUsage.updateUserInfo(updateMyself, user);
        }

    }


    /**
     * 自动获取sdk权限
     */

    private void autoObtainStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission
                    .READ_EXTERNAL_STORAGE}, STORAGE_PERMISSIONS_REQUEST_CODE);
        } else {
            PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
        }

    }

    private void showImages(Bitmap bitmap) {
        ivHead.setImageBitmap(bitmap);
    }

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }


    @Override
    public void onOk(boolean isMale) {
        User user = Util.user;
        if (isMale) {
            user.setSex("1");
        } else {
            user.setSex("0");
        }
        userRestUsage.updateUserInfo(updateMyself, user);
    }

    @Override
    public void onCancel() {

    }

    @Override
    public void pickValue(String value) {

        if (value.length() > 0) {
            tvCity.setText(value.substring(value.indexOf("-") + 1, value.length()));
            User user = Util.user;
            user.setAddress(value.substring(value.indexOf("-") + 1, value.length()));
            userRestUsage.updateUserInfo(updateMyself, user);
        }
    }
}
